//
//  ViewController.m
//  08-画板
//
//  Created by J on 16/3/24.
//  Copyright © 2016年 J. All rights reserved.
//

#import "ViewController.h"
#import "DrawView.h"
#import "ImageHandleView.h"//图片处理View

@interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet DrawView *drawView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}


- (IBAction)valueChange:(UISlider *)sender {
    //给画板传递线宽
    _drawView.lineWidth = sender.value;    
}

//点击按钮改变颜色 通过tag判断是哪个颜色
- (IBAction)colorChange:(UIButton *)sender {
    _drawView.pathColor = sender.backgroundColor;//把按钮的颜色赋值给画板 然后画板的颜色再赋值给贝塞尔线
}



- (IBAction)clear:(id)sender {//清屏
    [_drawView clear];
}


- (IBAction)remove:(id)sender {//撤销
    [_drawView remove];
}


- (IBAction)eraser:(id)sender {//橡皮擦  一根和背景相同颜色的线就行了 直接盖住之前的路径 这样视觉上看起来就像是橡皮擦 就像白色画板 上画白色线 其他线被盖住的时候 就显示跟画板一样的白色  看起来就像被擦除了一样
    _drawView.pathColor = _drawView.backgroundColor;
}



- (IBAction)Photo:(id)sender {//系统照片
    UIImagePickerController* pick = [[UIImagePickerController alloc]init];
    pick.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;//相册 UIImagePickerControllerSourceTypePhotoLibrary 相库
    pick.delegate = self;
    [self presentViewController:pick animated:YES completion:nil];
}



- (IBAction)save:(id)sender {//保存
    //layer渲染为图片 截屏
    //开启上下文
    UIGraphicsBeginImageContextWithOptions(_drawView.bounds.size, NO, 1.0);//不透明
    
    //获取上下文
    CGContextRef ref = UIGraphicsGetCurrentContext();
    
    //渲染涂层
    [_drawView.layer renderInContext:ref];
    
    //获取上下文中的图片
   UIImage* image =  UIGraphicsGetImageFromCurrentImageContext();
    //关闭上下文
    UIGraphicsEndImageContext();

    //写入相册
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}



//保存完成之后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {
        NSLog(@"%@",error);
    }else{
        NSLog(@"%@  保存成功",image);
    }
    
}


//获取照片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage* image = info[UIImagePickerControllerOriginalImage];
    
    //图片处理View
    ImageHandleView* imageHand = [[ImageHandleView alloc] initWithFrame:self.drawView.bounds];
    [self.drawView addSubview:imageHand];
    imageHand.image = image;//把图片传给透明的View 上面放着一个UIImageView

    
    [imageHand setHandleCompletionBlock:^(UIImage * image) {//图片处理完毕之后传回来
        self.drawView.image = image;
    }];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


@end
